import AuthComponent from '@/components/Authorized/AuthComponent';
import React, { useState, useEffect, useRef } from 'react';
import moment from 'moment'
import { useRequest } from '@umijs/hooks';
import { connect } from 'dva';
import ProTable from '@ant-design/pro-table';
import { Table, DatePicker, Select, Button, Modal, message, Radio } from 'antd';
import EditModal from '../EditModal'

import styles from './index.less'

import {
  getSpecialHeavyLuggageList,
  delSpecialHeavyLuggageItem,
  getHeavyLuggagePlaceSelectList,
  addSpecialHeavyLuggage,
  updateSpecialHeavyLuggage
} from '../../service';

function SpecialTable({ placeSelectData }) {

  const actionRef = useRef();
  const formRef = useRef();
  const [queryParams, setqueryParams] = useState({});
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [selectedRows, setselectedRows] = useState([]);
  const [editModalMsg, seteditModalMsg] = useState({ show: false, type: '', title: '', formItems: [], params: {} })
  // const [placeSelectData, setplaceSelectData] = useState([])


  const { run: addSpecialHeavyLuggageHandle } = useRequest((params) => addSpecialHeavyLuggage(params), {
    manual: true,
    onSuccess: res => {
      seteditModalMsg({ ...editModalMsg, show: false });
      reloadTable();
      message.success('新增成功');
    }
  })

  const { run: delSpecialHeavyLuggageItemHandle } = useRequest((params) => delSpecialHeavyLuggageItem(params), {
    manual: true,
    onSuccess: res => {
      seteditModalMsg({ ...editModalMsg, show: false });
      reloadTable();
      message.success('删除成功');
    }
  })

  const { run: updateSpecialHeavyLuggageHandle } = useRequest((params) => updateSpecialHeavyLuggage(params), {
    manual: true,
    onSuccess: res => {
      seteditModalMsg({ ...editModalMsg, show: false });
      reloadTable();
      message.success('修改成功');
    }
  })

  const classTypeMap = {
    A: '所有舱位',
    J: '经济舱',
    G: '公务舱'
  }
  const defaultParams = {
    classType: 'A',
    dstPlace: '',
    orgPlace: '',
    overWeightPrice: '',
    overWeightStandard: ''
  };
  const columns = [
    {
      title: '始发地', dataIndex: 'orgPlace',
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select showSearch style={{ width: '100%' }} {...rest}>
            {placeSelectData.map(item => (
              <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '到达地', dataIndex: 'dstPlace',
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select showSearch style={{ width: '100%' }} {...rest}>
            {placeSelectData.map(item => (
              <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '舱位类型', dataIndex: 'classType', hideInSearch: true,
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select style={{ width: '100%' }} {...rest}>
            <Select.Option value="A">合并舱位</Select.Option>
            <Select.Option value="J">经济舱</Select.Option>
            <Select.Option value="G">公务舱</Select.Option>
          </Select>
        );
      },
      render: (target, row, index, allData) => {
        return (
          <div>
            {classTypeMap[target] || target}
          </div>
        )
      },
    },
    {
      title: '逾重标准', dataIndex: 'overWeightStandard',
      render: (target, row, index, allData) => {
        return (
          <div>
            <span>{row.overWeightStandard}kg</span>
            <span style={{ marginLeft: '10px' }}>{row.overWeightPrice}CNY/kg</span>
          </div>
        )
      },
    },
  ]
  const modalFormItemsArr = [
    {
      label: '始发地',
      dataIndex: 'orgPlace',
      type: 'select',
      // value: '',
      selectArr: placeSelectData,
      placeholder: '请选择始发地'
    },
    {
      label: '到达站',
      dataIndex: 'dstPlace',
      type: 'select',
      // value: '',
      selectArr: placeSelectData,
      placeholder: '请选择到达站'
    },
    {
      label: '超重标准',
      dataIndex: 'overWeightStandard',
      type: 'input',
      suffix: 'kg',
      inputType: 'number',
      max: 3,
      placeholder: '请输入超重标准'
    },
    {
      label: '逾重价格',
      dataIndex: 'overWeightPrice',
      type: 'input',
      suffix: 'CNY/kg',
      inputType: 'number',
      max: 4,
      placeholder: '请输入逾重价格'
    },

  ];
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      // console.log(selectedRowKeys,selectedRows)
      setselectedRowKeys(selectedRowKeys);
      setselectedRows(selectedRows);
    },
  };
  const reloadTable = ()=>{
    setselectedRowKeys([]);
    actionRef.current.reload();
  }
  const addHandle = () => {
    seteditModalMsg({
      ...editModalMsg,
      show: true,
      title: '新增',
      type: 'specialAdd',
      formItems: modalFormItemsArr,
      params: defaultParams
    })
  }
  const delHandle = () => {
    let ids = selectedRows.map(item => item.id);
    if (ids.length > 0) {
      Modal.confirm({
        title: '提示',
        content: `确认删除选中的数据吗？`,
        onOk: () => {
          delSpecialHeavyLuggageItemHandle(ids);
        },
      });
    } else {
      message.error('删除操作需要勾选数据');
    }
  }

  const closeEditModal = () => {
    seteditModalMsg({
      ...editModalMsg,
      show: false,
      params: {}
    })
  }

  const editSava = (type, data) => {
    console.log(type, data);
    switch (type) {
      case 'specialAdd':
        delete data.id;
        addSpecialHeavyLuggageHandle({ ...data, classType: 'A' });
        break;
      case 'specialEdit':
        updateSpecialHeavyLuggageHandle({ ...data, classType: 'A' });
        break;
      default:
        
        break;
    }

  }

  const copyaddHandle = () => {
    if (selectedRows.length !== 1) {
      message.error('拷贝并新建操作需要勾选数据并且只能勾选一项');
      return
    }
    seteditModalMsg({
      ...editModalMsg,
      show: true,
      title: '新建',
      type: 'specialAdd',
      formItems: modalFormItemsArr,
      params: { ...defaultParams, ...selectedRows[0] }
    })
  }

  const editHandle = () => {
    if (selectedRows.length !== 1) {
      message.error('编辑操作需要勾选数据并且只能勾选一项');
      return
    }
    seteditModalMsg({
      ...editModalMsg,
      show: true,
      title: '编辑',
      type: 'specialEdit',
      formItems: modalFormItemsArr,
      params: { ...defaultParams, ...selectedRows[0] }
    })
  }
  const reLoadTable = () => {
    setTimeout(() => {
      setselectedRows([]);
    }, 0);
  }
  useEffect(() => {

    // getPlaceSelectList();
  }, [])
  return (
    <>
      {
        editModalMsg.show &&
        <EditModal
          editModalMsg={editModalMsg}
          onCancel={closeEditModal}
          editSava={editSava}>
        </EditModal>
      }
      <ProTable
        actionRef={actionRef}
        formRef={formRef}
        rowSelection={rowSelection}
        columns={columns}
        request={params => {
          return getSpecialHeavyLuggageList(params);
        }}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        rowKey="id"
        postData={data => data}
        toolBarRender={() => [
          <div className={styles.btnWrapper}>
            <AuthComponent authCode="mkt.heavyLuggage.special.save">
            <Button type="primary" onClick={addHandle}>新建</Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.heavyLuggage.special.update">
            <Button  onClick={editHandle}>编辑</Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.heavyLuggage.special.delete">
            <Button  onClick={delHandle}>删除</Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.heavyLuggage.special.save">
            <Button  onClick={copyaddHandle}>拷贝并新建</Button>
            </AuthComponent>
          </div>
        ]}
      ></ProTable>
    </>
  );
}

export default connect(({ heavyLuggage }) => {
  return {
    placeSelectData: heavyLuggage.placeSelectData
  }
})(SpecialTable);


